package com.lhy.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lhy.user.entity.User;
import com.lhy.user.feign.OrderVaccineFeign;
import com.lhy.user.feign.StockVaccineFeign;
import com.lhy.user.mapper.UserMapper;
import com.lhy.user.service.IUserService;
import com.lhy.user.vo.LoginVo;
import com.lhy.user.vo.RegisterVo;
import com.lhy.user.vo.RuleFormVo;
import com.lhy.vaccine_common.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    StockVaccineFeign stockVaccineFeign;

    @Autowired
    OrderVaccineFeign orderVaccineFeign;

    @Override
    public R login(LoginVo loginVo) {
        // 1.判断该用户是否注册
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("u_phone",loginVo.getAccount());

        User user = userMapper.selectOne(queryWrapper);
        if (user != null){
            // 2. 注册后允许登录
            return R.ok().put("data",user);
        }
        return R.error().put("data","201");
    }

    @Transactional
    @Override
    public R register(RegisterVo registerVo) {
        User user = new User();

        // 1.判断 城市或县镇是否为空
        user.setProvince(registerVo.getProvince());
        user.setCity(registerVo.getCity());
        if (!registerVo.getRegion().equals("")){
            user.setRegion(registerVo.getRegion());
        }

        // 2.将数据封装，进行数据校验，判断身份证是否重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("u_phone",registerVo.getAccount());

        User one = userMapper.selectOne(queryWrapper);
        if (one != null){
            return R.error().put("data","201"); // 已经注册，返回201
        }else{
            user.setName(registerVo.getName());
            user.setPhone(registerVo.getAccount());
            user.setTelephone(registerVo.getPassword());
            user.setGender(registerVo.getGender());
        }
        // 3. 校验完毕，进行insert操作
        int i = userMapper.insert(user);
        if (i == 1){
            return R.ok().put("data","200");
        }

        return R.error().put("data","203"); // 插入失败
    }

    @Override
    public R userGetVaccine() {
        // 1.远程调用 疫苗库存服务，获取疫苗列表，要去重之后的
        R vaccineFeignList = stockVaccineFeign.getUserVaccineList();
        if (vaccineFeignList.get("data") != null){
            return vaccineFeignList;
        }
        return R.error().put("500","请联系客服修复");
    }

    @Override
    public R order(RuleFormVo ruleFormVo) {
        // 首先要查到 vmsg 和 vid 填充到 ruleFormVo 中，所以，直接调用远程，在order服务中完成填充操作
        R r = orderVaccineFeign.userInsertOrder(ruleFormVo);
        return r;
    }
}
